<template>
  <div class="bom-container">
    <!-- 顶部操作栏 -->
    <div class="header-section">
      <div class="toolbar-left">
        <!-- <el-button type="text">展开全部</el-button>
        <el-button type="text">折叠全部</el-button> -->
        
      </div>
   
  
      <div class="toolbar-right">
        <el-button type="primary" @click="handleAdd">
          新增
        </el-button>
        <el-button type="default">
          导出
        </el-button>
        <el-button type="default">
          <el-icon><Setting /></el-icon>
        </el-button>
      </div>
    </div>
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
    <el-form-item label="编码">
      <el-input v-model="formInline.Materialcode" placeholder="请输入" clearable />
    </el-form-item>
   
    <el-form-item>
      <el-button type="primary" @click="GetBom">查询</el-button>
    </el-form-item>
  </el-form>

    <!-- 表格区域 -->
    <div class="table-section">
      <el-table
        :data="bomList"
        style="width: 100%"
        border
        stripe
        row-key="id"
        :tree-props="{ hasChildren: 'hasChildren', children: 'children' }"
      >
        <el-table-column prop="materialcode" label="编码" min-width="180" />
        <el-table-column prop="bname" label="名称" min-width="150" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="parentId" label="阶段" width="100" />
        <el-table-column prop="useNum" label="使用用量" width="100" />
        <el-table-column prop="describe" label="描述" min-width="150" />
        <el-table-column label="操作" width="280" fixed="right">
          <template v-slot="scope">
            <el-button type="text" class="action-btn" title="添加下级" @click="Addlower(scope.row)">
              添加下级
            </el-button>
            <el-button type="text" class="action-btn" @click="handleEdit(scope.row)" title="编辑">
              编辑
            </el-button>
            <el-button type="text" class="action-btn" title="绑定产品" v-if="scope.row.type === 'semi' || scope.row.type === 'upper'">
              绑定产品
            </el-button>
            <el-button type="text" class="action-btn delete-btn" @click="handleDelete(scope.row)" title="删除">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!-- 新增/编辑弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑' : '新增'"
      width="600px"
      :before-close="handleDialogClose"
    >
      <el-form
        ref="bomFormRef"
        :model="formData"
        label-width="100px"
      >
        <el-form-item label="编码" prop="code">
          <el-select v-model="formData.materialcode" placeholder="请选择编码" style="width: 100%" @change="handleCodeChange">
            <el-option
              v-for="option in codeOptions"
              :label="option.materialname"
              :value="option.materialcode"
            >
              <div class="option-content">
                <div class="option-type">{{ option.materialtypeName }}</div>
                <div class="option-name">{{ option.materialname }}</div>
              </div>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称" prop="name">
          <el-input v-model="formData.bname" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="版本" prop="version">
          <el-input v-model="formData.version" placeholder="请输入版本" />
        </el-form-item>
        <el-form-item label="使用数量" prop="useNum">
                <el-input-number v-model="formData.useNum" :min="0" :step="1" style="width: 100%" />
            </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input v-model="formData.describe" placeholder="请输入描述" type="textarea" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="handleSave">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 添加下级弹窗 - 穿梭框实现 -->
    <!-- 功能说明：从左侧表格勾选数据后通过箭头按钮转移到右侧表格，点击保存按钮将右侧数据保存到数据库 -->
    <el-dialog
      v-model="logic.isOpen"
      title="选择下级"
      width="1800px"
      height="600px"
      :before-close="handleDialogClose"
        
  
  
    >
      <el-container>
        <el-container>
          <!-- 左侧表格：显示可选的物料列表 -->
          <el-aside width="550px">
            <!-- 左侧表格标题 -->
            <div class="transfer-title">可选物料</div>
            <!-- 左侧表格：用于展示可选择的物料数据 -->
            <el-table
              ref="multipleTableRef"
              :data="tableData"
              v-model="logic.isDisOk"
              
              style="width: 100%"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection"   width="55" />
        <el-table-column prop="materialcode" label="编码" min-width="180" />
        <el-table-column prop="bname" label="名称" min-width="150" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="parentId" label="阶段" width="100" />
        <el-table-column prop="useNum" label="使用用量" width="100" />
        <el-table-column prop="describe" label="描述" min-width="150" />
            </el-table>
          </el-aside>
          
          <!-- 中间操作按钮区域 -->
          <div class="transfer-buttons">
            <!-- 右箭头按钮：将左侧选中的数据转移到右侧 -->
            <el-button type="primary" @click="handleToRight" :disabled="multipleSelection.length === 0">
              <el-icon><ArrowRight /></el-icon>
            </el-button>
            <!-- 左箭头按钮：将右侧选中的数据移回左侧 -->
            <el-button type="primary" @click="handleToLeft" :disabled="rightTableData.length === 0">
              <el-icon><ArrowLeft /></el-icon>
            </el-button>
          </div>
          
          <!-- 右侧表格：显示已选择的物料列表 -->
          <el-main width="550px">
            <!-- 右侧表格标题 -->
            <div class="transfer-title">已选物料</div>
            <!-- 右侧表格：用于展示已选择的物料数据 -->
            <el-table
              ref="rightTableRef"
              :data="rightTableData"
              style="width: 100%"
              @selection-change="handleRightSelectionChange"
            > <el-table-column type="selection"   width="55" />
               <el-table-column prop="materialcode" label="编码" min-width="180" />
        <el-table-column prop="bname" label="名称" min-width="150" />
        <el-table-column prop="version" label="版本" width="100" />
        <el-table-column prop="parentId" label="阶段" width="100" />
        <el-table-column prop="useNum" label="使用用量" width="100" />
        <el-table-column prop="describe" label="描述" min-width="150" />
            </el-table>
          </el-main>
        </el-container>
      </el-container>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleDialogClose">取消</el-button>
          <el-button type="primary" @click="save">确定</el-button>
        </span>
      </template>
    </el-dialog>
     
  
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Setting, ArrowRight, ArrowLeft } from '@element-plus/icons-vue'
import { APIs } from '../../Http/http'

// 表格数据
const bomList = ref<any[]>([])

// 弹窗相关
const dialogVisible = ref(false)
const isEdit = ref(false)
const bomFormRef = ref()
const parentId = ref(null)
// 编码选项
const codeOptions = ref<any[]>([])


onMounted(()=>{
  XL();
  GetBom();
})
const GetBom=()=>{
  APIs.get("/api/Read/ShowBom",{params:{Materialcode:formInline.Materialcode}}).then(res=>{
    bomList.value=res.data.data;
  })
}
const formInline=reactive({
Materialcode:""
})



const logic=reactive({
  isOpen:false,
  isDisOk:false,
  isShow:[{}]
})
// 表单数据
const formData = reactive({
  "materialcode": "",
  "bname": "",
  "version": null,
  "useNum":"",
  "describe": "",
  "parentId": null,
})

const multipleTableRef = ref() // 左侧表格引用
const rightTableRef = ref() // 右侧表格引用
const multipleSelection = ref<any[]>([])
const rightTableData = ref<any[]>([]) // 右侧表格数据
const currentRow = ref<any>(null) // 当前操作的行数据

const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val
  // 可选：同时保存到listrow以便调试
  listrow.value = val


 


}

/**
 * 处理右侧表格的选择变化事件
 * 功能说明：保存右侧表格中被选中的数据
 */
const handleRightSelectionChange = (val: any[]) => {
  rightSelectedData.value = val
  console.log(rightSelectedData.value);
}


const XL=()=>{
  APIs.get("/api/Read/GropWithType").then(res=>{
    codeOptions.value=res.data.data
  })
}

const listrow = ref<any[]>([])
// 新增
const handleAdd = async () => {
  isEdit.value = false
  parentId.value = null
  // 重置表单
  Object.assign(formData, {
    "materialcode": "",
    "bname":"",
    "version": null,
    "describe": "",
    "useNum":"",
    "parentId": null,
  })
  dialogVisible.value = true
}

// 编码变化处理函数
const handleCodeChange = (value: string) => {
  // 查找选中的编码对应的选项
  const selectedOption = codeOptions.value.find(option => option.materialcode === value);
  if (selectedOption) {
    // 自动填充名称字段
    formData.bname = selectedOption.materialname;
  }
}

// 编辑
const handleEdit = async (row: any) => {
  isEdit.value = true
  parentId.value = row.parentId
  Object.assign(formData, row)
  dialogVisible.value = true
}

// 删除
const handleDelete =(row:any) => {
    ElMessageBox.confirm(
    '确认删除吗?',
    '警告',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
     APIs.delete("/api/Write/DeleteBOM",{params:{bomId:row.bomId}
     }).then(res=>{
         if(res.data.code==100)
 {
     ElMessage.success(res.data.msg);
         GetBom();
 }
 else
 {
  ElMessage.error(res.data.msg);
  return;
 }
     })
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消操作',
      })
    })
}

const tableData=ref<any>([])

const generateData = () => {

 APIs.get("/api/Read/ShowBom",{params:{Materialcode:formInline.Materialcode || ''}}).then(res=>{
  tableData.value=res.data.data;
 })


}


const Addlower=(row:any)=>{
 currentRow.value = row; // 记录当前操作的行数据，用于保存时设置父节点ID
 generateData(); // 生成可选物料列表数据
 rightTableData.value = []; // 清空右侧表格数据，确保每次打开弹窗都是空的
 logic.isOpen=true; // 打开选择下级弹窗
}

/**
 * 处理从左侧表格向右转移数据
 * 功能说明：将左侧选中的数据添加到右侧表格，并为每个数据添加工序、数量和备注属性
 */
const handleToRight = () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请先选择要转移的数据')
    return
  }
  
  let addedCount = 0
  
  // 遍历左侧选中的数据
  multipleSelection.value.forEach((item) => {
    // 检查右侧表格中是否已存在相同的项
    const isExist = rightTableData.value.some(rightItem => rightItem.id === item.id || rightItem.productcode === item.productcode)
    
    if (!isExist) {
      // 如果不存在，则添加到右侧表格，并为其添加工序、数量和备注属性
      rightTableData.value.push({
        ...item,
      })
      addedCount++
      tableData.value.length--
    }
  })
  
  // 清空左侧表格的选择状态
  if (multipleTableRef.value) {
    multipleTableRef.value.clearSelection()
  }
  
  // 显示数据转移成功的提示
  if (addedCount > 0) {
    ElMessage.success(`成功转移${addedCount}条数据`)
  } 
}

// 添加右侧表格选中数据的引用
const rightSelectedData = ref<any[]>([])

/**
 * 处理从右侧表格向左转移数据
 * 功能说明：将右侧选中的数据移回到左侧表格，同时维护右侧表格的数据
 */
const handleToLeft = () => {
  if (rightSelectedData.value.length === 0) {
    ElMessage.warning('请先在右侧表格选择要移回的数据')
    return
  }
  
  let removedCount = 0
  
  // 创建一个新数组，排除右侧选中的数据
  const updatedRightData = rightTableData.value.filter(item => {
    const isRemoved = rightSelectedData.value.some(selectedItem => selectedItem.processId === item.processId)
    if (isRemoved) {
     
         rightSelectedData.value.length--;
    }
    else
    {
     tableData.value.length++;
    }
  
  })
  
  // 更新右侧表格数据
  rightTableData.value = updatedRightData
  
  // 清空右侧表格的选择状态
  if (rightTableRef.value) {
    rightTableRef.value.clearSelection()
  }
  
  // 显示数据移回成功的提示
  ElMessage.success(`成功移回${removedCount}条数据`)
}

/**
 * 保存右侧表格中的数据到数据库
 * 功能说明：将右侧表格中的数据转换为后端需要的格式，并调用API进行保存
 */
const save = () => {
  // 检查右侧表格是否有数据
  console.log("原始数据:", rightTableData.value); // 关键调试：确认数据源是否有值
if (!rightTableData.value || rightTableData.value.length === 0) {
  ElMessage.warning("没有选中的数据，请先选择数据");
  return; // 数据为空时直接返回，避免无效请求
}

  

  
  // 准备保存数据，转换为后端需要的格式
  // 注意：字段名需要与后端API要求保持一致（错误信息显示需要首字母大写的字段名）
const command = rightTableData.value.map(item => {
  // 打印每个item的结构，确认是否包含所需字段
  console.log("单个item数据:", item);
  return {
    materialcode: item.materialcode[0],       // 确认字段是否存在：item.productcode
    bname: item.bname[0],
    version:item.version[0],
    useNum:item.useNum[0],    // 确认字段是否存在：item.productName
    describe: item.describe[0]       // 确认字段是否存在：item.remark   // 确认字段是否存在：item.quantity               // 确认字段是否存在：item.process
  }; 
});
console.log("转换后待发送的数据:", command[0]);


// 3. 调用API并详细处理响应
 APIs.post('/api/Write/AddBomLower',command[0])

  .then(res => {
    if(res.data.code==100)
  {
ElMessage.success('添加失败');
  return;
   
  }
  else{
    ElMessage.success('添加成功');
  logic.isOpen = false;
  }
    // 调试：打印完整响应，查看后端返回的具体信息
    //console.log("API响应结果:", res);
  })
    // 检查响应格式是否正确（避免因后端返回格式异常导致判断错误）
  /* if (res && res.data) {
      if (res.data.code == 100) {
        ElMessage.success('添加成功');
        logic.isOpen = false;
        GetBom(); // 重新获取列表
      } else {
        // 显示后端返回的具体错误信息（如果有）
        ElMessage.error(`添加失败：${res.data.msg || '未知错误'}`);
      }
    } else {
      ElMessage.error('添加失败：后端返回格式异常');
    }
  })
  .catch(error => {
    // 详细打印网络错误信息
    console.error('请求错误详情:', error);
  
  }); */
}

// 保存表单
const handleSave = async () => {
  if (!bomFormRef.value) return
  
  {
    await bomFormRef.value.validate()
    
    let response
    const submitData = {
      ...formData
    }
    console.log(formData)
    if (isEdit.value) {
      response = await APIs.post('/api/Write/UpdateBOM', submitData)
    } else {
      response = await APIs.post('/api/Write/AddBOM', submitData)
    }
    
    if (response.data.code === 100) {
      ElMessage.success(isEdit.value ? '更新成功' : '新增成功')
      dialogVisible.value = false
      // getBOMList()
    } else {
      ElMessage.error(isEdit.value ? '更新失败' : '新增失败')
    }
  }
}

// 关闭弹窗
const handleDialogClose = () => {
 dialogVisible.value = false
 logic.isOpen=false
}
</script>

<style scoped>
.bom-container {
  background: white;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #fafafa;
  border-bottom: 1px solid #e4e7ed;
}

.toolbar-left {
  display: flex;
  gap: 15px;
}

.toolbar-right {
  display: flex;
  gap: 10px;
}

.table-section {
  flex: 1;
  overflow: auto;
}

:deep(.el-table .el-table__fixed-right) {
  height: 100% !important;
}

.action-btn {
  color: #409eff;
}

.delete-btn {
  color: #f56c6c;
}

/* 下拉框选项布局样式 */
:deep(.el-select-dropdown__item) {
  height: auto;
  min-height: 36px;
  display: flex;
  align-items: center;
}

.option-content {
  display: flex;
  width: 100%;
  align-items: center;
}

.option-type {
  background-color: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 4px;
  margin-right: 10px;
  min-width: 60px;
  text-align: center;
  font-size: 12px;
}

.option-name {
  flex: 1;
}

/* 选中状态样式 */
:deep(.el-select-dropdown__item.selected) .option-type {
  background-color: #bae7ff;
  color: #0958d9;
}

/* 穿梭框相关样式 */
.transfer-title {
  font-size: 14px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 10px;
  padding: 0 5px;
  height: 30px;
  line-height: 30px;
}

.transfer-buttons {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  padding: 0 15px;
  gap: 10px;
  height: 100%;
  min-height: 200px;
}

.transfer-buttons .el-button {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0;
  transition: all 0.3s ease;
}

.transfer-buttons .el-button:hover:not(:disabled) {
  transform: scale(1.1);
  box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
}

.transfer-buttons .el-button:disabled {
  opacity: 0.5;
}

/* 确保右侧表格宽度正确 */
.el-main {
  padding: 0 !important;
  background-color: #fff;
}

/* 表格单元格样式 */
:deep(.el-table__cell) {
  padding: 8px !important;
  border-bottom: 1px solid #f0f0f0;
}

/* 确保弹窗内表格可滚动 */
.el-dialog__body {
  height: calc(100% - 120px);
  overflow: auto;
  padding: 15px !important;
}

/* 确保表格在弹窗内显示完整 */
.el-dialog .el-table {
  max-height: calc(100vh - 300px);
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

/* 编辑框样式优化 */
.el-table .el-input {
  width: 100%;
}

/* 工序选择器样式 */
.el-table .el-select {
  width: 100%;
}

/* 优化左侧表格容器 */
.el-aside {
  background-color: #fff;
  border-right: 1px solid #ebeef5;
  padding-right: 10px;
}

/* 优化表格头部样式 */
:deep(.el-table__header th) {
  background-color: #fafafa !important;
  font-weight: 500;
}

/* 优化弹窗布局 */
.el-container {
  height: 100%;
}

.el-container > .el-container {
  height: 100%;
  display: flex;
  align-items: stretch;
}
</style>